const moment = require('../../utils/moment')
let app = getApp()
// 获取云数据库引用
const db = wx.cloud.database()
const admin = db.collection('adminlist')
let signUp = []

// 打卡日历页面
Page({

  /**
   * 页面的初始数据
   */
  data: {
    signUp: [],
    days: [],
    curYear: 0,
    curMonth: 0,
    curDate: 0,
    monthCount: 0,
    _id: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    // 获取当前年月
    const curYear = moment().year()
    const curMonth = moment().month() + 1
    const curDate = moment().date()
    const weeksCh = ['日', '一', '二', '三', '四', '五', '六']
    this.setData({
      curYear,
      curMonth,
      curDate,
      weeksCh
    })
    this.calculateEmptyGrids(curYear, curMonth)
    this.calculateDays(curYear, curMonth)
    // 获取当前用户当前任务的签到状态
    this.onGetSignUp()
  },

  // 获取当月共多少天
  getThisMonthDays (year, month) {
    return new Date(year, month, 0).getDate()
  },

  // 获取当月第一天星期几
  getFirstDayOfWeek (year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay()
  },

  // 计算当月1号前空了几个格子，把它填充在days数组的前面
  calculateEmptyGrids (year, month) {
    let that = this
    // 计算每个月时要清零
    that.setData({ days: [] })
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month)
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        let obj = {
          date: null,
          isSign: false
        }
        that.data.days.push(obj)
      }
      this.setData({
        days: that.data.days
      })
    // 清空
    } else {
      this.setData({
        days: []
      })
    }
  },

  // 绘制当月天数占的格子，并把它放到days数组中
  calculateDays (year, month) {
    let that = this
    const thisMonthDays = this.getThisMonthDays(year, month)
    for (let i = 1; i <= thisMonthDays; i++) {
      let obj = {
        date: i,
        isSign: false
      }
      that.data.days.push(obj)
    }
    this.setData({
      days: that.data.days
    })
  },

  // 匹配判断当月与当月哪些日子签到打卡
  onJudgeSign () {
    let that = this
    if (signUp !== undefined) {
      let signs = signUp
      let daysArr = that.data.days
      let monthCount = 0
      for (let i = 0; i < signs.length; i++) {
        // console.log(signs[i])
        let year = parseInt(signs[i] / 10000)
        let month = parseInt(signs[i] % 10000 / 100)
        let day = signs[i] % 100
        for (let j = 0; j < daysArr.length; j++) {
          // 年月日相同并且已打卡
          if (year === that.data.curYear && month === that.data.curMonth && daysArr[j].date === day) {
            daysArr[j].isSign = true
            monthCount++
          }
        }
      }
      that.setData({
        days: daysArr,
        monthCount: monthCount
      })
    }
  },

  // 切换控制年月，上一个月，下一个月
  handleCalendar (e) {
    const handle = e.currentTarget.dataset.handle
    const curYear = this.data.curYear
    const curMonth = this.data.curMonth
    if (handle === 'prev') {
      let newMonth = curMonth - 1
      let newYear = curYear
      if (newMonth < 1) {
        newYear = curYear - 1
        newMonth = 12
      }
      this.setData({
        curYear: newYear,
        curMonth: newMonth
      })
      this.calculateEmptyGrids(newYear, newMonth)
      this.calculateDays(newYear, newMonth)
      this.onGetSignUp()
    } else {
      let newMonth = curMonth + 1
      let newYear = curYear
      if (newMonth > 12) {
        newYear = curYear + 1
        newMonth = 1
      }
      this.setData({
        curYear: newYear,
        curMonth: newMonth
      })
      this.calculateEmptyGrids(newYear, newMonth)
      this.calculateDays(newYear, newMonth)
      this.onGetSignUp()
    }
  },

  // 获取当前用户的打卡数组以及打卡次数
  onGetSignUp () {
    let that = this
    let _id = JSON.parse(wx.getStorageSync('loginMsg'))._id
    if (_id !== undefined) {
      admin.doc(_id).get({
        success (res) {
          // res.data 包含该记录的数据
          signUp = res.data.signUp
          that.setData({
            signUp: signUp
          })
          // 获取后就判断签到情况
          that.onJudgeSign()
        }
      })
    }
  }
})